package space.panker916.event;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import space.panker916.pojo.DiscussPost;
import space.panker916.pojo.Event;
import space.panker916.pojo.Message;
import space.panker916.service.DiscussPostService;
import space.panker916.service.ElasticsearchService;
import space.panker916.service.MessageService;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static space.panker916.utils.Constants.*;

@Component
public class EventConsumer {

    private static final Logger logger = LoggerFactory.getLogger(EventConsumer.class);

    @Autowired
    private MessageService messageService;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private ElasticsearchService elasticsearchService;


    /**
     * 记录系统通知的功能（注意：需要将系统通知也存储在 message 中）
     *
     * @param record 从 队列 中取到的数据
     */

    @KafkaListener(topics = {TOPIC_COMMENT, TOPIC_LIKE, TOPIC_FOLLOW})
    public void handleAllMessage(ConsumerRecord record) throws JsonProcessingException {
        // 收到生产者传来的消息
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        String messageLog = messageIsError(record, event);
        if (messageLog != null) {
            logger.error(messageLog);
            return;
        }

        // 发送站内通知
        Message message = new Message();
        message.setFromId(SYSTEM_USER_ID);
        message.setToId(event.getEntityUserId());
        message.setConversationId(event.getTopic());
        message.setCreateTime(new Date());

        Map<String, Object> content = new HashMap<>();
        content.put("userId", event.getUserId());
        content.put("entityType", event.getEntityType());
        content.put("entityId", event.getEntityId());

        // entrySet 就是将 Map 中的 键值对 都放入一个 Set（Set里面的类型就是键值对） 中，使其可以遍历
        for (Map.Entry<String, Object> entry : event.getData().entrySet()) {
            content.put(entry.getKey(), entry.getValue());
        }

        // 将 content 转化为 JSON 字符串
        message.setContent(JSON.toJSONString(content));

        // 存储
        messageService.addMessage(message);
    }

    /**
     * 消费发帖事件
     */
    @KafkaListener(topics = {TOPIC_PUBLISH})
    public void handlePublishMessage(ConsumerRecord record) {
        // 收到生产者传来的消息
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        String messageLog = messageIsError(record, event);
        if (messageLog != null) {
            logger.error(messageLog);
            return;
        }

        DiscussPost discussPost = discussPostService.findDiscussPostById(event.getEntityId());
        elasticsearchService.saveDiscussPost(discussPost);
    }

    // 消费删帖事件
    @KafkaListener(topics = {TOPIC_DELETE})
    public void handleDeleteMessage(ConsumerRecord record) {
        // 收到生产者传来的消息
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        String messageLog = messageIsError(record, event);
        if (messageLog != null) {
            logger.error(messageLog);
            return;
        }

        elasticsearchService.deleteDiscussPost(event.getEntityId());
    }


    private String messageIsError(ConsumerRecord record, Event event) {
        if (record == null || record.value() == null) return "消息的内容为空";
        if (event == null) return "消息格式错误";
        return null;
    }
}
